const express = require('express');
const { JSDOM } = require('jsdom');
const { SVG, registerWindow } = require('@svgdotjs/svg.js');

// 导入 JSCAD 相关模块
const { primitives, booleans, transforms } = require('@jscad/modeling');
const { cube, sphere, cylinder } = primitives;
const { union, difference, intersection } = booleans;
const { translate, rotate, scale } = transforms;

const app = express();
const port = 3000;

// 设置 DOM 环境（SVG.js 需要 DOM 环境）
function setupDOM() {
    const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
    global.window = dom.window;
    global.document = dom.window.document;
}

// 初始化 DOM
setupDOM();
registerWindow(window, document);

// 设置静态文件服务
app.use(express.static('public'));

// JSCAD 模型生成函数
function createSimpleModel() {
    const myCube = cube({ size: 10 });
    const mySphere = translate([5, 5, 10], sphere({ radius: 3 }));
    const model = union(myCube, mySphere);
    return model;
}

function createComplexModel() {
    const base = cube({ size: [30, 30, 5] });
    const pillar1 = translate([5, 5, 2.5], cylinder({ height: 20, radius: 3 }));
    const pillar2 = translate([25, 5, 2.5], cylinder({ height: 20, radius: 3 }));
    const pillar3 = translate([5, 25, 2.5], cylinder({ height: 20, radius: 3 }));
    const pillar4 = translate([25, 25, 2.5], cylinder({ height: 20, radius: 3 }));
    const top = translate([0, 0, 25], cube({ size: [30, 30, 5] }));
    const structure = union(base, pillar1, pillar2, pillar3, pillar4, top);
    const decoration = translate([15, 15, 32], sphere({ radius: 4 }));
    return union(structure, decoration);
}

function createGearModel() {
    const gearBase = cylinder({ height: 5, radius: 20 });
    const centerHole = cylinder({ height: 7, radius: 8 });
    let teeth = [];
    for (let i = 0; i < 12; i++) {
        const angle = (i / 12) * Math.PI * 2;
        const tooth = translate([18 * Math.cos(angle), 18 * Math.sin(angle), 0], cube({ size: [4, 2, 5] }));
        teeth.push(tooth);
    }
    const gearWithTeeth = union(gearBase, ...teeth);
    return difference(gearWithTeeth, translate([0, 0, -1], centerHole));
}

// 路由1: 基础 SVG 生成
app.get('/svg', (req, res) => {
    const { width = 400, height = 300, text = 'Hello SVG' } = req.query;
    const draw = SVG().size(parseInt(width), parseInt(height));
    
    const gradient = draw.gradient('linear', function(add) {
        add.stop(0, '#667eea');
        add.stop(1, '#764ba2');
    });
    
    draw.rect(width, height).fill(gradient);
    
    const textElement = draw.plain(text);
    textElement.font({ size: 24, fill: '#fff' });
    textElement.attr('x', 50);
    textElement.attr('y', 150);
    
    draw.circle(80).move(300, 50).fill('rgba(255,255,255,0.2)').stroke({ color: '#fff', width: 2 });
    
    res.setHeader('Content-Type', 'image/svg+xml');
    res.send(draw.svg());
});

// 路由2: 柱状图 SVG
app.get('/chart', (req, res) => {
    const draw = SVG().size(500, 300);
    const data = [30, 60, 90, 120, 150, 180];
    const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD'];
    
    draw.rect(500, 300).fill('#f8f9fa');
    
    data.forEach((value, index) => {
        draw.rect(40, value).move(80 + index * 60, 250 - value).fill(colors[index]).stroke({ color: '#333', width: 1 });
        const textElement = draw.plain(value.toString());
        textElement.font({ size: 12, family: 'Arial', fill: '#333' });
        textElement.attr('x', 95 + index * 60);
        textElement.attr('y', 240 - value);
    });
    
    const textElement = draw.plain('销售数据图表');
    textElement.font({ size: 20, family: 'Arial', fill: '#333', weight: 'bold' });
    textElement.attr('x', 180);
    textElement.attr('y', 30);
    
    res.setHeader('Content-Type', 'image/svg+xml');
    res.send(draw.svg());
});

// 路由3: 饼图 SVG
app.get('/pie', (req, res) => {
    const draw = SVG().size(400, 300);
    const data = [
        { value: 40, color: '#FF6B6B', label: '产品 A' },
        { value: 25, color: '#4ECDC4', label: '产品 B' },
        { value: 20, color: '#45B7D1', label: '产品 C' },
        { value: 15, color: '#96CEB4', label: '产品 D' }
    ];
    
    let currentAngle = 0;
    const total = data.reduce((sum, item) => sum + item.value, 0);
    const centerX = 150;
    const centerY = 150;
    const radius = 80;
    
    data.forEach((item, index) => {
        const angle = (item.value / total) * 360;
        const endAngle = currentAngle + angle;
        const startRad = (currentAngle - 90) * Math.PI / 180;
        const endRad = (endAngle - 90) * Math.PI / 180;
        const x1 = centerX + radius * Math.cos(startRad);
        const y1 = centerY + radius * Math.sin(startRad);
        const x2 = centerX + radius * Math.cos(endRad);
        const y2 = centerY + radius * Math.sin(endRad);
        const largeArc = angle > 180 ? 1 : 0;
        const pathData = [`M ${centerX} ${centerY}`, `L ${x1} ${y1}`, `A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2}`, 'Z'].join(' ');
        draw.path(pathData).fill(item.color).stroke({ color: '#fff', width: 2 });
        currentAngle = endAngle;
    });
    
    data.forEach((item, index) => {
        draw.rect(15, 15).move(250, 80 + index * 25).fill(item.color);
        const textElement = draw.plain(`${item.label}: ${item.value}%`);
        textElement.font({ size: 12, family: 'Arial', fill: '#333' });
        textElement.attr('x', 270);
        textElement.attr('y', 92 + index * 25);    
    });
    
    res.setHeader('Content-Type', 'image/svg+xml');
    res.send(draw.svg());
});

// JSCAD 模型信息页面
app.get('/jscad/info', (req, res) => {
    const { model = 'simple' } = req.query;
    let modelName = model === 'complex' ? '复杂结构模型' : model === 'gear' ? '齿轮模型' : '简单立方体+球体模型';
    
    res.send(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>JSCAD 模型信息 - ${modelName}</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 40px; }
                .info { background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0; }
                .btn { display: inline-block; padding: 10px 20px; margin: 5px; background: #007bff; color: white; text-decoration: none; border-radius: 5px; }
                .btn:hover { background: #0056b3; }
                .code { background: #333; color: #fff; padding: 15px; border-radius: 5px; font-family: monospace; margin: 10px 0; }
            </style>
        </head>
        <body>
            <h1>JSCAD 3D 模型信息</h1>
            <div class="info">
                <h2>${modelName}</h2>
                <p><strong>模型类型:</strong> ${model}</p>
                <p><strong>生成时间:</strong> ${new Date().toLocaleString()}</p>
                <p><strong>状态:</strong> 模型生成功能正常</p>
            </div>
            <div class="code">const model = create${model.charAt(0).toUpperCase() + model.slice(1)}Model();</div>
            <a class="btn" href="/jscad/preview?model=${model}">3D 预览</a>
            <a class="btn" href="/">返回首页</a>
        </body>
        </html>
    `);
});

// 3D 预览页面 - 修复版本
app.get('/jscad/preview', (req, res) => {
    const { model = 'simple' } = req.query;
    let modelName = model === 'complex' ? '复杂结构模型' : model === 'gear' ? '齿轮模型' : '简单立方体+球体模型';
    
    res.send(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>3D 预览 - ${modelName}</title>
            <meta charset="utf-8">
            <style>
                * { margin: 0; padding: 0; box-sizing: border-box; }
                body { 
                    font-family: Arial, sans-serif;
                    background: #1a1a2e;
                    color: white;
                    overflow: hidden;
                    height: 100vh;
                }
                .container {
                    display: flex;
                    height: 100vh;
                    width: 100vw;
                }
                .sidebar {
                    width: 300px;
                    background: rgba(255, 255, 255, 0.1);
                    padding: 20px;
                    border-right: 1px solid rgba(255, 255, 255, 0.2);
                    overflow-y: auto;
                }
                .viewer {
                    flex: 1;
                    position: relative;
                }
                #webgl {
                    width: 100%;
                    height: 100%;
                    display: block;
                }
                .controls {
                    margin-top: 20px;
                }
                .control-group {
                    margin-bottom: 15px;
                }
                label {
                    display: block;
                    margin-bottom: 5px;
                    font-weight: bold;
                }
                input[type="range"] {
                    width: 100%;
                }
                .btn {
                    display: inline-block;
                    padding: 10px 20px;
                    margin: 5px;
                    background: #007bff;
                    color: white;
                    text-decoration: none;
                    border-radius: 5px;
                    border: none;
                    cursor: pointer;
                    font-size: 14px;
                }
                .btn:hover {
                    background: #0056b3;
                }
                .model-info {
                    background: rgba(255, 255, 255, 0.1);
                    padding: 15px;
                    border-radius: 8px;
                    margin-bottom: 20px;
                }
                .loading {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    text-align: center;
                    background: rgba(0, 0, 0, 0.8);
                    padding: 20px;
                    border-radius: 10px;
                    z-index: 1000;
                }
                .error {
                    color: #ff6b6b;
                    background: rgba(255, 107, 107, 0.1);
                    padding: 10px;
                    border-radius: 5px;
                    margin: 10px 0;
                }
                .success {
                    color: #4ecdc4;
                    background: rgba(78, 205, 196, 0.1);
                    padding: 10px;
                    border-radius: 5px;
                    margin: 10px 0;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="sidebar">
                    <h2>${modelName}</h2>
                    <div class="model-info">
                        <p><strong>模型类型:</strong> ${model}</p>
                        <p><strong>状态:</strong> <span id="status">初始化中...</span></p>
                        <div id="webglStatus" class="loading">检查 WebGL 支持...</div>
                    </div>
                    
                    <div class="controls">
                        <div class="control-group">
                            <label>旋转速度: <span id="speedValue">1.0</span></label>
                            <input type="range" id="rotationSpeed" min="0" max="2" step="0.1" value="1">
                        </div>
                        
                        <div class="control-group">
                            <label>缩放: <span id="scaleValue">1.0</span></label>
                            <input type="range" id="scale" min="0.5" max="3" step="0.1" value="1">
                        </div>
                        
                        <div class="control-group">
                            <label>线框模式:</label>
                            <input type="checkbox" id="wireframe">
                        </div>
                        
                        <button class="btn" onclick="resetView()">重置视图</button>
                        <button class="btn" onclick="toggleRotation()" id="rotationBtn">暂停旋转</button>
                        <button class="btn" onclick="changeModel('simple')">简单模型</button>
                        <button class="btn" onclick="changeModel('complex')">复杂模型</button>
                        <button class="btn" onclick="changeModel('gear')">齿轮模型</button>
                    </div>
                    
                    <div style="margin-top: 20px;">
                        <a class="btn" href="/jscad/info?model=${model}">模型信息</a>
                        <a class="btn" href="/">返回首页</a>
                    </div>
                </div>
                
                <div class="viewer">
                    <canvas id="webgl"></canvas>
                    <div class="loading" id="loading">
                        <h3>正在加载 3D 模型...</h3>
                        <p>初始化 WebGL 渲染环境</p>
                        <div id="initProgress"></div>
                    </div>
                </div>
            </div>

            <!-- 使用更稳定的 Three.js 版本 -->
            <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
            <script>
                // Three.js 核心变量
                let scene, camera, renderer, modelGroup;
                let isRotating = true;
                let rotationSpeed = 1.0;
                
                // 更新状态显示
                function updateStatus(message, type = 'info') {
                    const statusEl = document.getElementById('status');
                    const webglStatusEl = document.getElementById('webglStatus');
                    
                    statusEl.textContent = message;
                    webglStatusEl.textContent = message;
                    webglStatusEl.className = type;
                    
                    if (type === 'success') {
                        webglStatusEl.style.display = 'none';
                    }
                }
                
                // 检查 WebGL 支持
                function checkWebGLSupport() {
                    updateStatus('检查 WebGL 支持...');
                    
                    try {
                        const canvas = document.createElement('canvas');
                        const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
                        
                        if (!gl) {
                            throw new Error('WebGL not supported');
                        }
                        
                        updateStatus('WebGL 支持正常', 'success');
                        return true;
                    } catch (error) {
                        updateStatus('错误: ' + error.message, 'error');
                        return false;
                    }
                }
                
                // 初始化 Three.js 场景
                function initThreeJS() {
                    updateStatus('正在初始化 Three.js...');
                    
                    try {
                        // 1. 创建场景
                        scene = new THREE.Scene();
                        scene.background = new THREE.Color(0x1a1a2e);
                        
                        // 2. 创建相机
                        const canvas = document.getElementById('webgl');
                        const width = canvas.clientWidth;
                        const height = canvas.clientHeight;
                        
                        camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
                        camera.position.set(20, 15, 20);
                        camera.lookAt(0, 0, 0);
                        
                        // 3. 创建渲染器
                        renderer = new THREE.WebGLRenderer({ 
                            canvas: canvas,
                            antialias: true,
                            alpha: true
                        });
                        renderer.setSize(width, height);
                        renderer.setPixelRatio(window.devicePixelRatio);
                        
                        updateStatus('渲染器创建成功', 'success');
                        
                        // 4. 添加灯光
                        setupLights();
                        
                        // 5. 添加辅助工具
                        setupHelpers();
                        
                        // 6. 创建模型
                        createModel('${model}');
                        
                        // 7. 隐藏加载界面
                        document.getElementById('loading').style.display = 'none';
                        
                        // 8. 开始动画循环
                        animate();
                        
                        updateStatus('3D 场景初始化完成', 'success');
                        
                    } catch (error) {
                        updateStatus('初始化错误: ' + error.message, 'error');
                        console.error('Three.js 初始化错误:', error);
                    }
                }
                
                // 设置灯光
                function setupLights() {
                    const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
                    scene.add(ambientLight);
                    
                    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
                    directionalLight.position.set(10, 20, 15);
                    scene.add(directionalLight);
                    
                    const pointLight = new THREE.PointLight(0x4a90e2, 0.5, 100);
                    pointLight.position.set(-10, 10, -10);
                    scene.add(pointLight);
                }
                
                // 设置辅助工具
                function setupHelpers() {
                    const gridHelper = new THREE.GridHelper(50, 50, 0x444444, 0x222222);
                    scene.add(gridHelper);
                    
                    const axesHelper = new THREE.AxesHelper(10);
                    scene.add(axesHelper);
                }
                
                // 创建模型
                function createModel(modelType) {
                    // 移除现有模型
                    if (modelGroup) {
                        scene.remove(modelGroup);
                    }
                    
                    modelGroup = new THREE.Group();
                    
                    switch(modelType) {
                        case 'complex':
                            createComplexGeometry();
                            break;
                        case 'gear':
                            createGearGeometry();
                            break;
                        default:
                            createSimpleGeometry();
                    }
                    
                    scene.add(modelGroup);
                    updateStatus('模型创建完成: ' + modelType, 'success');
                }
                
                // 创建简单几何体
                function createSimpleGeometry() {
                    // 立方体
                    const cubeGeometry = new THREE.BoxGeometry(10, 10, 10);
                    const cubeMaterial = new THREE.MeshPhongMaterial({ 
                        color: 0x4ecdc4,
                        transparent: true,
                        opacity: 0.9
                    });
                    const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
                    modelGroup.add(cube);
                    
                    // 球体
                    const sphereGeometry = new THREE.SphereGeometry(3, 32, 32);
                    const sphereMaterial = new THREE.MeshPhongMaterial({ 
                        color: 0xff6b6b,
                        transparent: true,
                        opacity: 0.9
                    });
                    const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
                    sphere.position.set(5, 5, 10);
                    modelGroup.add(sphere);
                }
                
                // 创建复杂几何体
                function createComplexGeometry() {
                    // 基础平台
                    const baseGeometry = new THREE.BoxGeometry(30, 5, 30);
                    const baseMaterial = new THREE.MeshPhongMaterial({ color: 0xff6b6b });
                    const base = new THREE.Mesh(baseGeometry, baseMaterial);
                    base.position.y = 2.5;
                    modelGroup.add(base);
                    
                    // 支柱
                    const pillarGeometry = new THREE.CylinderGeometry(3, 3, 20, 16);
                    const pillarMaterial = new THREE.MeshPhongMaterial({ color: 0x4ecdc4 });
                    
                    const pillarPositions = [
                        [5, 12.5, 5], [25, 12.5, 5], 
                        [5, 12.5, 25], [25, 12.5, 25]
                    ];
                    
                    pillarPositions.forEach(pos => {
                        const pillar = new THREE.Mesh(pillarGeometry, pillarMaterial);
                        pillar.position.set(pos[0], pos[1], pos[2]);
                        modelGroup.add(pillar);
                    });
                    
                    // 顶部平台
                    const topGeometry = new THREE.BoxGeometry(30, 5, 30);
                    const topMaterial = new THREE.MeshPhongMaterial({ color: 0x45b7d1 });
                    const top = new THREE.Mesh(topGeometry, topMaterial);
                    top.position.y = 27.5;
                    modelGroup.add(top);
                    
                    // 装饰球体
                    const sphereGeometry = new THREE.SphereGeometry(4, 32, 32);
                    const sphereMaterial = new THREE.MeshPhongMaterial({ color: 0xffe66d });
                    const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
                    sphere.position.set(15, 34, 15);
                    modelGroup.add(sphere);
                }
                
                // 创建齿轮几何体
                function createGearGeometry() {
                    // 齿轮主体
                    const gearGeometry = new THREE.CylinderGeometry(20, 20, 5, 32);
                    const gearMaterial = new THREE.MeshPhongMaterial({ color: 0x96ceb4 });
                    const gear = new THREE.Mesh(gearGeometry, gearMaterial);
                    modelGroup.add(gear);
                    
                    // 齿轮齿
                    const toothGeometry = new THREE.BoxGeometry(4, 2, 5);
                    const toothMaterial = new THREE.MeshPhongMaterial({ color: 0xff6b6b });
                    
                    for (let i = 0; i < 12; i++) {
                        const angle = (i / 12) * Math.PI * 2;
                        const tooth = new THREE.Mesh(toothGeometry, toothMaterial);
                        tooth.position.set(
                            18 * Math.cos(angle),
                            0,
                            18 * Math.sin(angle)
                        );
                        tooth.rotation.y = -angle;
                        modelGroup.add(tooth);
                    }
                    
                    // 中心孔
                    const holeGeometry = new THREE.CylinderGeometry(8, 8, 7, 32);
                    const holeMaterial = new THREE.MeshPhongMaterial({ color: 0x2d2d2d });
                    const hole = new THREE.Mesh(holeGeometry, holeMaterial);
                    hole.position.y = -1;
                    modelGroup.add(hole);
                }
                
                // 动画循环
                function animate() {
                    requestAnimationFrame(animate);
                    
                    if (isRotating && modelGroup) {
                        modelGroup.rotation.y += 0.01 * rotationSpeed;
                    }
                    
                    renderer.render(scene, camera);
                }
                
                // 重置视图
                function resetView() {
                    if (camera) {
                        camera.position.set(20, 15, 20);
                        camera.lookAt(0, 0, 0);
                    }
                }
                
                // 切换旋转
                function toggleRotation() {
                    isRotating = !isRotating;
                    document.getElementById('rotationBtn').textContent = 
                        isRotating ? '暂停旋转' : '开始旋转';
                }
                
                // 切换模型
                function changeModel(modelType) {
                    window.location.href = '/jscad/preview?model=' + modelType;
                }
                
                // 事件监听
                document.getElementById('rotationSpeed').addEventListener('input', function(e) {
                    rotationSpeed = parseFloat(e.target.value);
                    document.getElementById('speedValue').textContent = rotationSpeed.toFixed(1);
                });
                
                document.getElementById('scale').addEventListener('input', function(e) {
                    const scaleValue = parseFloat(e.target.value);
                    document.getElementById('scaleValue').textContent = scaleValue.toFixed(1);
                    if (modelGroup) {
                        modelGroup.scale.set(scaleValue, scaleValue, scaleValue);
                    }
                });
                
                document.getElementById('wireframe').addEventListener('change', function(e) {
                    if (modelGroup) {
                        modelGroup.traverse(function(child) {
                            if (child.isMesh) {
                                child.material.wireframe = e.target.checked;
                            }
                        });
                    }
                });
                
                // 窗口大小调整
                window.addEventListener('resize', function() {
                    if (camera && renderer) {
                        const canvas = document.getElementById('webgl');
                        camera.aspect = canvas.clientWidth / canvas.clientHeight;
                        camera.updateProjectionMatrix();
                        renderer.setSize(canvas.clientWidth, canvas.clientHeight);
                    }
                });
                
                // 页面加载完成后初始化
                window.addEventListener('load', function() {
                    updateStatus('页面加载完成，开始初始化...');
                    
                    if (checkWebGLSupport()) {
                        // 给一点延迟确保所有资源加载完成
                        setTimeout(initThreeJS, 100);
                    }
                });
            </script>
        </body>
        </html>
    `);
});

// 首页
app.get('/', (req, res) => {
    res.send(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>SVG.js + JSCAD Express 服务器</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 40px; }
                .section { margin: 30px 0; padding: 20px; border-left: 4px solid #007bff; background: #f8f9fa; }
                .link { display: block; margin: 10px 0; padding: 10px; background: #f0f0f0; text-decoration: none; color: #333; border-radius: 5px; }
                .link:hover { background: #e0e0e0; }
                .category { color: #007bff; font-weight: bold; }
            </style>
        </head>
        <body>
            <h1>SVG.js + JSCAD Express 服务器示例</h1>
            <p>点击以下链接查看不同的生成示例：</p>
            
            <div class="section">
                <div class="category">📊 SVG 生成</div>
                <a class="link" href="/svg" target="_blank">基础 SVG</a>
                <a class="link" href="/svg?width=600&height=400&text=自定义文本" target="_blank">带参数的基础 SVG</a>
                <a class="link" href="/chart" target="_blank">柱状图</a>
                <a class="link" href="/pie" target="_blank">饼图</a>
            </div>
            
            <div class="section">
                <div class="category">🎯 JSCAD 3D 模型生成</div>
                <a class="link" href="/jscad/info?model=simple" target="_blank">简单 3D 模型</a>
                <a class="link" href="/jscad/info?model=complex" target="_blank">复杂 3D 模型</a>
                <a class="link" href="/jscad/info?model=gear" target="_blank">齿轮 3D 模型</a>
                <a class="link" href="/jscad/preview?model=simple" target="_blank">3D 实时预览</a>
            </div>
        </body>
        </html>
    `);
});

// 启动服务器
app.listen(port, () => {
    console.log(`🚀 SVG + JSCAD 服务器运行在 http://localhost:${port}`);
    console.log(`📊 可用路由:`);
    console.log(`   http://localhost:${port}/ - 首页`);
    console.log(`   http://localhost:${port}/svg - 基础 SVG`);
    console.log(`   http://localhost:${port}/chart - 柱状图`);
    console.log(`   http://localhost:${port}/pie - 饼图`);
    console.log(`🎯 JSCAD 3D 模型:`);
    console.log(`   http://localhost:${port}/jscad/info - 模型信息`);
    console.log(`   http://localhost:${port}/jscad/preview - 3D 实时预览`);
});